<?php

class Crud_Form_Decorator_Tree extends Zend_Form_Decorator_Abstract 
{
	/**
	 * @var Tree
	 */
	protected $_tree;
	
	protected $_checked;
	
	/**
     * Decorate content and/or element
     *
     * @param  string $content
     * @return string
     * @throws Zend_Form_Decorator_Exception when unimplemented
     */
	public function render($content)
	{
		preg_match_all('/value="(\d+)" checked="checked"/is', $content, $matches);
		$this->_checked = $matches[1];
		
		$tree = $this->getTree();
		
		$rootNodes = $tree->_rootNodes;
		
		$content = '<ul class="tree">';
		foreach ($rootNodes as $rootNodeId) {
			$content .= $this->_appendContent($tree, $rootNodeId);
		}
		$content .= '</ul>';
		
		return $content;
	}
	
	protected function _appendContent(Tree $tree, $treeNode)
	{
		if (!$treeNode instanceof TreeNode) {
			$treeNode = $tree->getNodeById($treeNode);
		}
		
		$content = '';
		$rootNode = $tree->getNodeById($treeNode->getId());
			
		$id = $rootNode->getId();
		$element = $rootNode->getElement();
		$value = $element['value'];
		
		$checked = '';
		if (in_array($id, $this->_checked)) {
			$checked = ' checked="checked"';
		}
		
		$name = $this->getElement()->getName();
		$content .= "<li><label><input type='checkbox' name='{$name}[]' value='$id'$checked/>$value</label>";
		
		$childs = $treeNode->getChilds();
		if (count($childs)) {
			$content .= '<ul>';
			foreach ($childs as $child) {
				$content .= $this->_appendContent($tree, $child);
			}
			$content .= '</ul>';
		}
		
		$content .= "</li>";
		
		return $content;
	}
	
	public function setTree(Tree $tree)
	{
		$this->_tree = $tree;
	}
	
	/**
	 * @return Tree
	 */
	public function getTree()
	{
		return $this->_tree;
	}
	
}